package com.songshuai.webapi.common.aop;

import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import org.apache.commons.logging.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by yubo on 2018/12/18
 */
public class BaseLogAspect {


    public Object getLogAspectForm(ProceedingJoinPoint pjp,Log logger) {
        // 接收到请求，记录请求内容
        StringBuffer logBuffer = new StringBuffer();
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容

        logBuffer.append("[");
        logBuffer.append("URL=" + request.getRequestURI().toString());
        logBuffer.append(";");
        logBuffer.append(" HTTP_METHOD=" + request.getMethod());
        logBuffer.append(";");
        logBuffer.append(" IP=" + request.getRemoteAddr());
        logBuffer.append(";");
        logBuffer.append(" CLASS_METHOD=" + pjp.getSignature().getDeclaringTypeName() + "."
                + pjp.getSignature().getName());
        logBuffer.append(";");
        logBuffer.append(" ARGS=" + Arrays.toString(pjp.getArgs()));


        // logger.info(logBuffer);
        Long startDate = System.currentTimeMillis();
        // 执行方法
        Object o = null;
        try {
            o = (QueryResponse<?>) pjp.proceed();
        }
        catch (BusinessException ex){
            o=QueryResponse.setResData(null, ex.getCode(),ex.getMessage());
        }
        catch (Throwable t) {
            t.printStackTrace();
            o=QueryResponse.setResData(null, ResultStatus.FAIL,"系统运行时异常");
            logger.error("系统运行时异常" + t);
        }
        Long endDate = System.currentTimeMillis();
        logBuffer.append(";");
        logBuffer.append(" TIME=" + (endDate - startDate));
        logBuffer.append("]");
        logger.info(logBuffer.toString());
        return o;
    }
}
